#pragma once
#include <iostream>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <memory>
// #include "Command.hpp"

#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns
{
    using namespace log_ns;
    class Socket;
    using SockSPtr = std::shared_ptr<Socket>;
    const static int gblcklog = 8;
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR
    };

    // 模版方法类模式：
    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int backlog = gblcklog) = 0;
        virtual SockSPtr Accepter(InetAddr *clientaddr) = 0;
        virtual bool Connector( std::string peerip, uint16_t peerport) = 0;
        virtual int Sockfd() = 0;
        virtual void Close() = 0;
        virtual ssize_t Recv(std::string *out) = 0;
        virtual ssize_t Send(const std::string &in) = 0;

    public:
        // 创建监听套接字
        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();
            CreateBindOrDie(port);
            CreateListenOrDie();
        }
        // 创建客户端套接字
        bool BuildClientSocket(std::string peerip, uint16_t peerport)
        {
            CreateSocketOrDie();
            // Connector(peerip, peerport);
            return Connector(peerip, peerport);
        }
        // void BuildUdpSocket()
        // {}

    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        {
        }
        TcpSocket(int sockfd) : _sockfd(sockfd)
        {
        }
        // 创建套接字
        void CreateSocketOrDie() override
        {
            // 1.创建socket
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socker create error\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);
        }

        // 绑定、本地socket信息、端口和IP
        void CreateBindOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));

            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;
            // 2.绑定sockfd 和 socket addr
            if (::bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind error \n");
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success \n");
        }
        // 监听
        void CreateListenOrDie(int backlog) override
        {
            // 让套接字设置为listen状态
            if (::listen(_sockfd, gblcklog))
            {
                LOG(FATAL, "listen error \n");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen success \n");
        }
        SockSPtr Accepter(InetAddr *clientaddr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 4.获取新链接
            // 从监听套接字获取新的套接字、获取客户端信息
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            // 获取连接失败、继续获取
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return nullptr;
            }
            *clientaddr = InetAddr(client);
            // 获客成功，提供服务
            return std::make_shared<TcpSocket>(sockfd);
        }
        // 链接客户端服务器
        // peerip远端ip、peerport远端port
        bool Connector( std::string peerip, uint16_t peerport) override
        { // 2.不需要显示的bind，但是一定要有自己的IP和port，所以需要隐式的bind，OS会自动bind sockfd，用自己的IP和随机算口号
            // 什么时候进行自动bind,if the connection or binding succeeds
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            // server.sin_addr.s_addr =
            // 进程序列转为网络序列
            ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                // 连接失败
                std::cerr << "connect socket error" << std::endl;
                return false;
            }
            return true;
        }
        int Sockfd()
        {
            return _sockfd;
        }
        void Close()
        {
            if (_sockfd > 0)
            {
                ::close(_sockfd);
            }
        }
        // 还需调整
        ssize_t Recv(std::string *out) override
        {
            // 缺点：inbuffer不是动态的，每次只能读取这么多，或者说，明明只发了5个字节，但是却还是要读取1023个字节
            char inbuffer[4096];
            // n是实际读取的字节数                                   // 当做字符串
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0); //(留一个\n的位置)
            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }

        ssize_t Send(const std::string &in) override
        {
            return ::send(_sockfd, in.c_str(), in.size(), 0);
        }
        ~TcpSocket()
        {
        }

    private:
        int _sockfd; // 可以是listen套接字、也可以是普通套接字
    };
}